document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const tabs = {
        base64: document.getElementById('base64-tab'),
        url: document.getElementById('url-tab'),
        unicode: document.getElementById('unicode-tab'),
        html: document.getElementById('html-tab')
    };
    
    const operations = {
        encode: document.getElementById('encode-op'),
        decode: document.getElementById('decode-op')
    };
    
    const inputText = document.getElementById('input-text');
    const outputText = document.getElementById('output-text');
    const copyButton = document.getElementById('copy-result');
    const clearButton = document.getElementById('clear-input');
    const addExampleButton = document.getElementById('add-example');
    const operationDesc = document.getElementById('operation-desc');
    const encodingDescription = document.getElementById('encoding-description');
    
    // 当前状态
    let currentTab = 'base64';
    let currentOperation = 'encode';
    
    // 编码描述信息
    const descriptions = {
        base64: {
            title: 'Base64编码说明',
            content: 'Base64是一种基于64个可打印字符来表示二进制数据的表示方法，常用于HTTP环境下传输二进制数据，如图片或其他媒体文件。'
        },
        url: {
            title: 'URL编码说明',
            content: 'URL编码将字符转换为可在URL中安全传输的格式，例如空格被转换为%20，特殊字符被转换为十六进制值。'
        },
        unicode: {
            title: 'Unicode编码说明',
            content: 'Unicode编码支持世界上几乎所有的文字系统，可以将字符转换为\\uXXXX格式的Unicode编码或从Unicode编码转换回字符。'
        },
        html: {
            title: 'HTML编码说明',
            content: 'HTML编码用于在网页中安全显示特殊字符，例如将<转换为&lt;，>转换为&gt;等，防止HTML注入攻击。'
        }
    };
    
    // 操作描述信息
    const operationDescriptions = {
        base64: {
            encode: '将文本编码为Base64字符串',
            decode: '将Base64字符串解码为文本'
        },
        url: {
            encode: '将文本编码为URL安全格式',
            decode: '将URL编码的文本解码为原始文本'
        },
        unicode: {
            encode: '将文本转换为Unicode编码',
            decode: '将Unicode编码转换为文本'
        },
        html: {
            encode: '将文本转换为HTML实体编码',
            decode: '将HTML实体编码转换为文本'
        }
    };
    
    // 示例文本
    const examples = {
        base64: {
            encode: 'Hello, World! 你好，世界！',
            decode: 'SGVsbG8sIFdvcmxkISDkvaDlpb3vvIzkuJbnlYwh'
        },
        url: {
            encode: 'https://example.com?name=测试&id=123',
            decode: 'https%3A%2F%2Fexample.com%3Fname%3D%E6%B5%8B%E8%AF%95%26id%3D123'
        },
        unicode: {
            encode: '你好，Unicode！',
            decode: '\u4f60\u597d\uff0cUnicode\uff01'
        },
        html: {
            encode: '<div>Hello & World</div>',
            decode: '&lt;div&gt;Hello &amp; World&lt;/div&gt;'
        }
    };
    
    // 编码/解码函数
    const encoders = {
        base64: {
            encode: text => btoa(unescape(encodeURIComponent(text))),
            decode: text => {
                try {
                    return decodeURIComponent(escape(atob(text)));
                } catch (e) {
                    return '解码错误：输入的不是有效的Base64字符串';
                }
            }
        },
        url: {
            encode: text => encodeURIComponent(text),
            decode: text => {
                try {
                    return decodeURIComponent(text);
                } catch (e) {
                    return '解码错误：输入的不是有效的URL编码字符串';
                }
            }
        },
        unicode: {
            encode: text => {
                let result = '';
                for (let i = 0; i < text.length; i++) {
                    const hex = text.charCodeAt(i).toString(16);
                    result += '\\u' + '0000'.substring(0, 4 - hex.length) + hex;
                }
                return result;
            },
            decode: text => {
                try {
                    return text.replace(/\\u([\da-f]{4})/gi, (match, grp) => {
                        return String.fromCharCode(parseInt(grp, 16));
                    });
                } catch (e) {
                    return '解码错误：输入的不是有效的Unicode编码字符串';
                }
            }
        },
        html: {
            encode: text => {
                const el = document.createElement('div');
                el.textContent = text;
                return el.innerHTML;
            },
            decode: text => {
                const el = document.createElement('div');
                el.innerHTML = text;
                return el.textContent;
            }
        }
    };
    
    // 更新UI函数
    function updateUI() {
        // 更新标签状态
        Object.keys(tabs).forEach(tab => {
            tabs[tab].classList.toggle('active', tab === currentTab);
        });
        
        // 更新操作状态
        Object.keys(operations).forEach(op => {
            operations[op].classList.toggle('active', op === currentOperation);
        });
        
        // 更新操作描述
        operationDesc.textContent = operationDescriptions[currentTab][currentOperation];
        
        // 更新编码说明
        encodingDescription.innerHTML = `<h5>${descriptions[currentTab].title}</h5><p>${descriptions[currentTab].content}</p>`;
        
        // 处理输入文本
        processInput();
    }
    
    // 处理输入文本
    function processInput() {
        const input = inputText.value;
        if (input) {
            const result = encoders[currentTab][currentOperation](input);
            outputText.value = result;
        } else {
            outputText.value = '';
        }
    }
    
    // 绑定标签点击事件
    Object.keys(tabs).forEach(tab => {
        tabs[tab].addEventListener('click', () => {
            currentTab = tab;
            updateUI();
        });
    });
    
    // 绑定操作点击事件
    Object.keys(operations).forEach(op => {
        operations[op].addEventListener('click', () => {
            currentOperation = op;
            updateUI();
        });
    });
    
    // 绑定输入事件
    inputText.addEventListener('input', processInput);
    
    // 绑定复制按钮事件
    copyButton.addEventListener('click', () => {
        if (outputText.value) {
            outputText.select();
            document.execCommand('copy');
            // 显示复制成功提示
            const originalText = copyButton.textContent;
            copyButton.textContent = '已复制！';
            setTimeout(() => {
                copyButton.textContent = originalText;
            }, 1500);
        }
    });
    
    // 绑定清空按钮事件
    clearButton.addEventListener('click', () => {
        inputText.value = '';
        outputText.value = '';
    });
    
    // 绑定示例按钮事件
    addExampleButton.addEventListener('click', () => {
        inputText.value = examples[currentTab][currentOperation];
        processInput();
    });
    
    // 初始化UI
    updateUI();
});